import { login, logout, getInfo, get_super_role } from "@/api/login";
import {
  getToken,
  setToken,
  removeToken,
  removePermissionToken,
  setPermissionToken
} from "@/utils/auth";
import { exportData } from "@/api/report/index";
import { resetRouter } from "@/router";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";

const getDefaultState = () => {
  return {
    userInfo: {
      show_original_order_data: 1,
      is_batch: 0
    },
    token: getToken(),
    name: "",
    avatar: "",
    nav: [],
    companyInfo: "",
    // 分拣语音播报
    sortVoiceSwitch: 0,
    site_title: "",
    localnav: [],
    remember: "",
    // 合约期
    is_expired: 0,
    // 首页的排序
    indexSetting: "",
    contract_period: "",
    // 是否需要支付佣金
    domestic: {},
    // 设备商城地址
    shop_url: "",
    //有更新跳转地址
    document_url: "",
    document_status: 0,
    // 系统练习
    system_exercise: {},
    // 续费地址
    contract_period_url: "",
    wx_customer_service: "",
    //导出列表
    controlExport: false,
    record_id: "",
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState());
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_NAV: (state, nav) => {
    state.nav = nav;
  },
  SET_COMINFO: (state, info) => {
    state.companyInfo = info;
  },
  SET_SORTVOICESWITCH: (state, data) => {
    state.sortVoiceSwitch = Number(data);
  },
  SET_SITE_TITLE: (state, info) => {
    state.site_title = info;
  },
  SET_REMEMBER: (state, remember) => {
    state.remember = remember;
  },
  SET_INDEX_SETTING: (state, indexSetting) => {
    state.indexSetting = indexSetting;
  },
  SET_CONTRACT_PERIOD: (state, contract_period) => {
    state.contract_period = contract_period;
  },
  SET_IS_EXPIRED: (state, is_expired) => {
    state.is_expired = is_expired;
  },
  SET_DOMESTIC: (state, domestic) => {
    state.domestic = domestic;
  },
  SET_SHOP_URL: (state, shop_url) => {
    state.shop_url = shop_url;
  },
  SET_SYSTEM_EXERCISE: (state, system_exercise) => {
    state.system_exercise = system_exercise;
  },
  SET_CONTRACT_PERIOD_URL: (state, contract_period_url) => {
    state.contract_period_url = contract_period_url;
  },
  SET_DOCUMENT_URL: (state, document_url) => {
    state.document_url = document_url;
  },
  SET_DOCUMENT_STATUS: (state, document_status) => {
    state.document_status = document_status;
  },
  // wx_customer_service
  SET_WX_SERVICE: (state, wx_customer_service) => {
    state.wx_customer_service = wx_customer_service;
  },
  // 保存导出的id
  SET_RECORDID: (state, data) => {
    console.log(data, 11111);
    
    state.record_id = data
  },
  // 控制导入导出公共模态框展示隐藏
  SET_CONTROLEXPORT: (state, data) => {
    state.controlExport = data
  },
};

const actions = {
  // 导出列表
  exportData({ commit }, data) {
    // 将传递来的data缓存下来，在通知后端的接口中需要用到
    localStorage.setItem("exportParams",JSON.stringify(data))
    let query = Object.assign(
      {
        sign: Md5(
          objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
        ),
      },
      apiUrl().name,
      data
    );
    exportData(query).then((res) => {
      if (res.errcode == 0) {
        commit("SET_RECORDID", res.data.record_id);
        commit("SET_CONTROLEXPORT", true);
      }
    });
  },
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo)
        .then(response => {
          if (response.errcode == 0) {
            commit("SET_TOKEN", response.data.token);
            if (state.remember) {
              setToken(response.data.token, state.remember);
            } else {
              setToken(response.data.token);
            }
          }
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  //user 记住密码
  remember({ commit }, remember) {
    commit("SET_REMEMBER", remember);
  },
  // user token
  token({ commit }, token) {
    commit("SET_TOKEN", token);
    setToken(token);
  },

  // user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(
        Object.assign(
          { sign: Md5(objKeySort(apiUrl().name) + apiUrl().appsecret) },
          apiUrl().name
        )
      )
        .then(response => {
          setPermissionToken(JSON.stringify(response.data.userInfo.domestic));
          commit("SET_USERINFO", response.data.userInfo);
          commit("SET_CONTRACT_PERIOD_URL", response.data.contract_period_url);
          commit("SET_NAME", response.data.userInfo.name);
          commit("SET_CONTRACT_PERIOD", response.data.userInfo.contract_period);
          commit("SET_IS_EXPIRED", response.data.is_expired);
          commit("SET_DOMESTIC", response.data.userInfo.domestic);
          commit("SET_AVATAR", response.data.userInfo);
          commit("SET_NAV", response.data.spe_nav);
          commit("SET_COMINFO", response.data.info);
          commit("SET_SORTVOICESWITCH", response.data.info.sort_voice_switch);
          commit("SET_SITE_TITLE", response.data.site_title);
          commit("SET_INDEX_SETTING", response.data.indexSetting);
          commit("SET_SHOP_URL", response.data.shop_url);
          commit("SET_DOCUMENT_URL", response.data.document_url);
          commit("SET_DOCUMENT_STATUS", response.data.document_status);
          commit("SET_WX_SERVICE", response.data.wx_customer_service);
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // 获取系统联系登录接口
  get_super_role({ commit, state }) {
    return new Promise((resolve, reject) => {
      get_super_role(
        Object.assign(
          { sign: Md5(objKeySort(apiUrl().name) + apiUrl().appsecret) },
          apiUrl().name
        )
      )
        .then(response => {
          if (response.errcode == 0) {
            commit("SET_SYSTEM_EXERCISE", response.data);
          }
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(
        Object.assign(
          { sign: Md5(objKeySort(apiUrl().name) + apiUrl().appsecret) },
          apiUrl().name
        )
      )
        .then(() => {
          removeToken(); // must remove  token  first
          resetRouter();
          removePermissionToken();
          commit("RESET_STATE");
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
